﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace System.Web.Mvc.Html
{
    public static class Validation
    {
        public static MvcHtmlString ValidationSummaryAlt(this HtmlHelper helper)
        {
            StringBuilder error = new StringBuilder();
            if (helper.ViewData.ModelState.IsValid)
                return null;
            error.Append("<p>Falló la validación, revise lo siguiente</p>");
            error.Append("<ul>");
            foreach (KeyValuePair<string, ModelState> m in helper.ViewData.ModelState.Where(m => m.Value.Errors.Count > 0))
            {
                string display = helper.ViewData.ModelMetadata.Properties.Single(p => p.PropertyName.Equals(m.Key)).DisplayName;
                foreach (ModelError e in m.Value.Errors)
                {
                    error.AppendFormat("<li>{0}</li>", ((display != null && !display.Equals("")) ? "<strong>" + display + "</strong>" + ": " : "") + e.ErrorMessage);
                }
            }
            error.Append("</ul>");

            StringBuilder summary = new StringBuilder();
            summary.Append("<div id=\"validation-message-failure\" class=\"validation-alt\"></div>");
            summary.Append("<script type=\"text/javascript\">");
            summary.Append("ponerMensaje('validation', '" + error.ToString() + "', true, 10000)");
            summary.Append("</script>");
            return MvcHtmlString.Create(summary.ToString());
        }
    }
}
